package start.demo01.xml.domain;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import io.lettuce.core.ScriptOutputType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class DOMParseXml {
	public static List<Book> parseXml(InputStream is){
		List<Book> list = new ArrayList<>();
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(is);
			Element root = document.getDocumentElement();
			String textContent = root.getTextContent();
			System.out.println(textContent);
			NodeList nodes = root.getElementsByTagName("book");
			for(int i = 0; i < nodes.getLength(); i++) {
				Book book = new Book();
				Element node =  (Element)nodes.item(i);
				System.out.println(node.getTextContent());
				Integer id = Integer.valueOf(node.getAttribute("id"));
				book.setId(id);
				NodeList childNodes = node.getChildNodes();
				for(int j = 0; j < childNodes.getLength(); j++) {
					//Element childNode =  (Element)childNodes.item(j);
					if(childNodes.item(j).getNodeType() == Node.ELEMENT_NODE){
						Element childNode =  (Element)childNodes.item(j);
						if("a".equals(childNode.getTagName())) {
							String src = childNode.getAttribute("src");
							System.out.println(src);
						}
//						if("name".equals(childNode.getTagName()))
//							book.setName(childNode.getTextContent());
//						if("author".equals(childNode.getTagName()))
//							book.setAuthor(childNode.getTextContent());
//						if("publisher".equals(childNode.getTagName()))
//							book.setPublisher(childNode.getTextContent());
//						if("price".equals(childNode.getTagName()))
//							book.setPrice(Float.parseFloat(childNode.getTextContent()));
					}
				}
				list.add(book);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public static void main(String[] args) throws FileNotFoundException {
		BufferedInputStream is = new BufferedInputStream(new FileInputStream("books.xml"));
//		parseXml(is).forEach(System.out::println);;
		parseXml(is);
	}
}
